<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lishx.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"hide","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="什么是Cookie cookie翻译过来是饼干的意思。 cookie是服务器通知客户端保存键值对的一种技术，这些信息由客户端保存 客户端有了cookie之后可以发送给服务器 每个cookie的大小不得超过4kb">
<meta property="og:type" content="article">
<meta property="og:title" content="Cookie与Session">
<meta property="og:url" content="lishx.com/2020/08/23/java/cookie-session/index.html">
<meta property="og:site_name" content="lishouxian&#39;s BLOG">
<meta property="og:description" content="什么是Cookie cookie翻译过来是饼干的意思。 cookie是服务器通知客户端保存键值对的一种技术，这些信息由客户端保存 客户端有了cookie之后可以发送给服务器 每个cookie的大小不得超过4kb">
<meta property="og:locale">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gi1ozspa7uj31m50u0qbd.jpg">
<meta property="article:published_time" content="2020-08-23T13:20:00.000Z">
<meta property="article:modified_time" content="2020-09-05T08:53:00.795Z">
<meta property="article:author" content="李寿贤">
<meta property="article:tag" content="javaweb">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gi1ozspa7uj31m50u0qbd.jpg">

<link rel="canonical" href="lishx.com/2020/08/23/java/cookie-session/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>

  <title>Cookie与Session | lishouxian's BLOG</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">lishouxian's BLOG</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="lishx.com/2020/08/23/java/cookie-session/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="李寿贤">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="lishouxian's BLOG">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Cookie与Session
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2020-08-23 21:20:00" itemprop="dateCreated datePublished" datetime="2020-08-23T21:20:00+08:00">2020-08-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2020-09-05 16:53:00" itemprop="dateModified" datetime="2020-09-05T16:53:00+08:00">2020-09-05</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javaweb/" itemprop="url" rel="index"><span itemprop="name">javaweb</span></a>
                </span>
            </span>

          
            <span id="/2020/08/23/java/cookie-session/" class="post-meta-item leancloud_visitors" data-flag-title="Cookie与Session" title="Views">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">Views: </span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine: </span>
    
    <a title="valine" href="/2020/08/23/java/cookie-session/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/08/23/java/cookie-session/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="什么是Cookie"><a href="#什么是Cookie" class="headerlink" title="什么是Cookie"></a>什么是Cookie</h2><ol>
<li>cookie翻译过来是饼干的意思。</li>
<li>cookie是服务器通知客户端保存键值对的一种技术，这些信息由客户端保存</li>
<li>客户端有了cookie之后可以发送给服务器</li>
<li>每个cookie的大小不得超过4kb</li>
</ol>
<a id="more"></a>

<h2 id="Cookie的创建"><a href="#Cookie的创建" class="headerlink" title="Cookie的创建"></a>Cookie的创建</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">createCookie</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;chuang&quot;</span>);</span><br><span class="line">    <span class="comment">//创建cookie对象</span></span><br><span class="line">    Cookie cookie = <span class="keyword">new</span> Cookie(<span class="string">&quot;key1&quot;</span>,<span class="string">&quot;value1&quot;</span>);</span><br><span class="line">    <span class="comment">//通知客户端保存cookie</span></span><br><span class="line">    resp.addCookie(cookie);</span><br><span class="line">    resp.getWriter().write(<span class="string">&quot;cookie 创建成功&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Cookie的获取"><a href="#Cookie的获取" class="headerlink" title="Cookie的获取"></a>Cookie的获取</h2><h3 id="获取全部Cookie"><a href="#获取全部Cookie" class="headerlink" title="获取全部Cookie"></a>获取全部Cookie</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">getCookie</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;chuang&quot;</span>);</span><br><span class="line">    <span class="comment">//获取cookie对象</span></span><br><span class="line">    Cookie[] cookies = req.getCookies();</span><br><span class="line">    <span class="keyword">for</span> (Cookie cookie : cookies) &#123;</span><br><span class="line">        resp.getWriter().write(cookie.getName() +<span class="string">&quot;+&quot;</span>+ cookie.getValue() + <span class="string">&quot;&lt;br/&gt;&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="获取单个cookie"><a href="#获取单个cookie" class="headerlink" title="获取单个cookie"></a>获取单个cookie</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (Cookie cookie : cookies) &#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="string">&quot;cookieneededname&quot;</span> = cookie.getName())&#123;</span><br><span class="line">        resp.getWriter().write(cookie.getName() +<span class="string">&quot;+&quot;</span>+ cookie.getValue() + <span class="string">&quot;&lt;br/&gt;&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Cookie值的修改"><a href="#Cookie值的修改" class="headerlink" title="Cookie值的修改"></a>Cookie值的修改</h2><h3 id="方案一：重新创建"><a href="#方案一：重新创建" class="headerlink" title="方案一：重新创建"></a>方案一：重新创建</h3><ol>
<li>先创建一个要修改的同名的Cookie对象</li>
<li>在构造器中赋予新的Cookie值</li>
<li>调用<code>response。addCookie(Cookie)</code>通知客户端保存</li>
</ol>
<h3 id="方案二：使用API修改"><a href="#方案二：使用API修改" class="headerlink" title="方案二：使用API修改"></a>方案二：使用API修改</h3><ol>
<li>先查找到需要修改的Cookie对象</li>
<li>调用<code>setValue()</code>方法赋予新的Cookie值</li>
<li>调用<code>response。addCookie(Cookie)</code>通知客户端保存</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">updateCookie</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">    <span class="comment">//获取cookie对象</span></span><br><span class="line">    Cookie[] cookies = req.getCookies();</span><br><span class="line">    <span class="keyword">for</span> (Cookie cookie : cookies) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">&quot;cookieName&quot;</span>.equals(cookie.getName())) &#123;</span><br><span class="line">            cookie.setValue(<span class="string">&quot;okok&quot;</span>);</span><br><span class="line">            resp.addCookie(cookie);</span><br><span class="line">            resp.getWriter().write(cookie.getName() + <span class="string">&quot;+&quot;</span> + cookie.getValue() + <span class="string">&quot;&lt;br/&gt;&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Cookie-的生命控制"><a href="#Cookie-的生命控制" class="headerlink" title="Cookie 的生命控制"></a>Cookie 的生命控制</h2><p>Cookie的生命控制指如何管理Cookie什么时候被销毁(删除)</p>
<p><code>setMaxAge()</code></p>
<ul>
<li>正数，表示在指定的秒数后过期</li>
<li>负数，表示浏览器一关，cookie就会被删除(默认值就是-1)</li>
<li>零，表示马上删除Cookie</li>
</ul>
<p>无论设置何种生命控制都需要调用<code>resp.addCookie(cookie);</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">deleteNow</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">    <span class="comment">//获取cookie对象</span></span><br><span class="line">    Cookie[] cookies = req.getCookies();</span><br><span class="line">    <span class="keyword">for</span> (Cookie cookie : cookies) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">&quot;cookieName&quot;</span>.equals(cookie.getName())) &#123;</span><br><span class="line">            cookie.setMaxAge(<span class="number">0</span>);</span><br><span class="line">            resp.addCookie(cookie);</span><br><span class="line">            resp.getWriter().write(cookie.getName() + <span class="string">&quot;+&quot;</span> + cookie.getValue() + <span class="string">&quot;&lt;br/&gt;&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Cookie有效路径Path的设置"><a href="#Cookie有效路径Path的设置" class="headerlink" title="Cookie有效路径Path的设置"></a>Cookie有效路径Path的设置</h2><p>Cookie的path属性可以有效的过滤哪些Cookie可以发送给服务器，哪些不发</p>
<p>Path属性是通过请求的地址来进行有效的过滤。</p>
<table>
<thead>
<tr>
<th>CookieA</th>
<th>path=/cookie</th>
</tr>
</thead>
<tbody><tr>
<td>CookieB</td>
<td>path=/</td>
</tr>
</tbody></table>
<p>请求地址如下：</p>
<table>
<thead>
<tr>
<th><code>http://ip:port/工程路径/a.html</code></th>
<th>CookieA发送  CookieB不发送</th>
</tr>
</thead>
<tbody><tr>
<td><code>http://ip:port/工程路径/cookie/a.html</code></td>
<td>CookieA不发送  CookieB发送</td>
</tr>
</tbody></table>
<p>设置方法为：<code>cookie.setPath(req.getContextPath() + &quot;/cookie&quot;);</code></p>
<h2 id="什么是Session会话"><a href="#什么是Session会话" class="headerlink" title="什么是Session会话"></a>什么是Session会话</h2><ol>
<li>session就是一个接口(HttpSession)</li>
<li>Session就是会话，他用来维护一个客户端和服务器中间关联</li>
<li>每个客户端都有自己的一个Session会话</li>
<li>Session会话中，我们经常用来保存用户登录信息</li>
</ol>
<h2 id="如何创建Session和获取-ID号是否为新"><a href="#如何创建Session和获取-ID号是否为新" class="headerlink" title="如何创建Session和获取(ID号是否为新)"></a>如何创建Session和获取(ID号是否为新)</h2><p>创建Session和获取Session的API都是一样的。</p>
<p>request.getSession()</p>
<ul>
<li>第一次调用是：创建Session会话</li>
<li>之后：获取之前创建的Session会话</li>
</ul>
<p><code>isNew()</code>判断Session是否是新创建出来的</p>
<ul>
<li>true表示刚创建出来</li>
<li>FALSE表示获取之前创建</li>
</ul>
<p>每个Session都有一个身份证号。也就是ID值，这个ID值是唯一的</p>
<p><code>getId()</code>可以得到Session会话的ID值</p>
<h2 id="Session域数据的存取"><a href="#Session域数据的存取" class="headerlink" title="Session域数据的存取"></a>Session域数据的存取</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">setAttribute</span><span class="params">(HttpServletRequest req,HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">	req.getSession().setAttribute(<span class="string">&quot;key1&quot;</span>, <span class="string">&quot;value1&quot;</span>);</span><br><span class="line">	resp.getWriter().write(<span class="string">&quot;已经往 Session 中保存了数据&quot;</span>); &#125;</span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">getAttribute</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">	Object attribute = req.getSession().getAttribute(<span class="string">&quot;key1&quot;</span>);</span><br><span class="line">	resp.getWriter().write(<span class="string">&quot;从 Session 中获取出 key1 的数据是:&quot;</span> + attribute); &#125;</span><br></pre></td></tr></table></figure>

<h2 id="Session生命周期控制"><a href="#Session生命周期控制" class="headerlink" title="Session生命周期控制"></a>Session生命周期控制</h2><p><code>public void setMaxInactiveInterval(int interval)</code>设置Session的超时时间(以秒为单位)，超过指定时间，Session就会被销毁。</p>
<ul>
<li>值为正数时，设定Session的超时时长</li>
<li>值为负数时，设定Session永不超时(极少使用)</li>
</ul>
<p><code>public int getMaxInactiveInterval()</code>获取 Session 的超时时间</p>
<p><code>publicvoidinvalidate()</code>让当前Session会话马上超时无效。</p>
<p>Session的默认超时时长为30分钟</p>
<p>在 Tomcat 服务器的配置文件 web.xml 中默认有以下的配置，它就表示配置了当前 Tomcat 服务器下所有的 Session 超时配置默认时长为:30 分钟。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">session-config</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">session-timeout</span>&gt;</span>30<span class="tag">&lt;/<span class="name">session-timeout</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">session-config</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>若需要修改web工程默认的Session时长为其他值，可以自己在web.xml中修改上述配置</p>
<h2 id="Session的工作方式"><a href="#Session的工作方式" class="headerlink" title="Session的工作方式"></a>Session的工作方式</h2><p><img src="https://tva1.sinaimg.cn/large/007S8ZIlly1gi1ozspa7uj31m50u0qbd.jpg" alt="Session"></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/javaweb/" rel="tag"># javaweb</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/08/22/java/servlet/" rel="prev" title="JavaWeb之Servlet">
      <i class="fa fa-chevron-left"></i> JavaWeb之Servlet
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/08/28/java/jdbc1/" rel="next" title="JDBC(一)">
      JDBC(一) <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFCookie"><span class="nav-number">1.</span> <span class="nav-text">什么是Cookie</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cookie%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="nav-number">2.</span> <span class="nav-text">Cookie的创建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cookie%E7%9A%84%E8%8E%B7%E5%8F%96"><span class="nav-number">3.</span> <span class="nav-text">Cookie的获取</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%8E%B7%E5%8F%96%E5%85%A8%E9%83%A8Cookie"><span class="nav-number">3.1.</span> <span class="nav-text">获取全部Cookie</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%8E%B7%E5%8F%96%E5%8D%95%E4%B8%AAcookie"><span class="nav-number">3.2.</span> <span class="nav-text">获取单个cookie</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cookie%E5%80%BC%E7%9A%84%E4%BF%AE%E6%94%B9"><span class="nav-number">4.</span> <span class="nav-text">Cookie值的修改</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%9A%E9%87%8D%E6%96%B0%E5%88%9B%E5%BB%BA"><span class="nav-number">4.1.</span> <span class="nav-text">方案一：重新创建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B9%E6%A1%88%E4%BA%8C%EF%BC%9A%E4%BD%BF%E7%94%A8API%E4%BF%AE%E6%94%B9"><span class="nav-number">4.2.</span> <span class="nav-text">方案二：使用API修改</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cookie-%E7%9A%84%E7%94%9F%E5%91%BD%E6%8E%A7%E5%88%B6"><span class="nav-number">5.</span> <span class="nav-text">Cookie 的生命控制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cookie%E6%9C%89%E6%95%88%E8%B7%AF%E5%BE%84Path%E7%9A%84%E8%AE%BE%E7%BD%AE"><span class="nav-number">6.</span> <span class="nav-text">Cookie有效路径Path的设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFSession%E4%BC%9A%E8%AF%9D"><span class="nav-number">7.</span> <span class="nav-text">什么是Session会话</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BASession%E5%92%8C%E8%8E%B7%E5%8F%96-ID%E5%8F%B7%E6%98%AF%E5%90%A6%E4%B8%BA%E6%96%B0"><span class="nav-number">8.</span> <span class="nav-text">如何创建Session和获取(ID号是否为新)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Session%E5%9F%9F%E6%95%B0%E6%8D%AE%E7%9A%84%E5%AD%98%E5%8F%96"><span class="nav-number">9.</span> <span class="nav-text">Session域数据的存取</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Session%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E6%8E%A7%E5%88%B6"><span class="nav-number">10.</span> <span class="nav-text">Session生命周期控制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Session%E7%9A%84%E5%B7%A5%E4%BD%9C%E6%96%B9%E5%BC%8F"><span class="nav-number">11.</span> <span class="nav-text">Session的工作方式</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">李寿贤</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">李寿贤</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        






<script>
  (function() {
    function leancloudSelector(url) {
      url = encodeURI(url);
      return document.getElementById(url).querySelector('.leancloud-visitors-count');
    }

    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.id);
      var title = visitors.dataset.flagTitle;

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url })))
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
            leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .catch(error => {
                console.error('Failed to save visitor count', error);
              });
          } else {
              Counter('post', '/classes/Counter', { title, url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }

    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.id);
      });

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url: { '$in': entries } })))
        .then(response => response.json())
        .then(({ results }) => {
          for (let url of entries) {
            let target = results.find(item => item.url === url);
            leancloudSelector(url).innerText = target ? target.time : 0;
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }

    let { app_id, app_key, server_url } = {"enable":true,"app_id":"xb8ocBOeUvnh1ClRKD6b7Vwm-gzGzoHsz","app_key":"ODH211TGDI1jVYfBVxifNiXt","server_url":null,"security":false};
    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${api_server}/1.1${url}`, {
          method,
          headers: {
            'X-LC-Id'     : app_id,
            'X-LC-Key'    : app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    }

    let api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(response => response.json())
        .then(({ api_server }) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>


      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>















  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '9AvQGweVbH47hbtztejqnkta-gzGzoHsz',
      appKey     : 'lo0cfhvPh5MqPkgzHzT5n0Az',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
